package com.powernode.model;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.*;

/**
 * @description:
 * @author: mky
 * @date: 2024/7/5 11:13
 * @version: 1.0
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class LoginUserDetails implements UserDetails {
    private Long userId;

    private String username;

    private String password;

    private Integer status;
    private Long shopId;
    private String loginType;
    private Set<String> permissions;
    @JsonIgnore
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        permissions.forEach(perm -> {
            String[] split = perm.split(",");
            if (split.length == 1){
                grantedAuthorities.add(new SimpleGrantedAuthority(perm));
            }else {
                for (String s : split) {
                    grantedAuthorities.add(new SimpleGrantedAuthority(s));
                }
            }
        });
        return grantedAuthorities;
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public String getUsername() {
        return this.loginType + this.userId;
    }

    @Override
    public boolean isAccountNonExpired() {
        return this.status==1;
    }

    @Override
    public boolean isAccountNonLocked() {
        return this.status==1;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return this.status==1;
    }

    @Override
    public boolean isEnabled() {
        return this.status==1;
    }

    public Set<String> getPermissions() {
        Set<String> permissionList = new HashSet<>();
        permissions.forEach(perm -> {
            String[] split = perm.split(",");
            if (split.length == 1){
                permissionList.add(perm);
            }else {
                for (String s : split) {
                    permissionList.add(s);
                }
            }
        });
        return permissionList;
    }
}
